package com.moyo.repository;

import com.moyo.model.SysUserRole;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

/**
 * 用户-角色关联数据访问（内存实现，后续可替换为JPA/MyBatis）
 */
public class SysUserRoleRepository {
    private final Map<Long, SysUserRole> userRoleMap = new HashMap<>();
    private final AtomicLong idGen = new AtomicLong(1);

    public SysUserRole save(SysUserRole userRole) {
        if (userRole.getId() == null) {
            userRole.setId(idGen.getAndIncrement());
        }
        userRoleMap.put(userRole.getId(), userRole);
        return userRole;
    }

    public Optional<SysUserRole> findById(Long id) {
        return Optional.ofNullable(userRoleMap.get(id));
    }

    public List<SysUserRole> findByUserId(Long userId) {
        return userRoleMap.values().stream()
                .filter(ur -> ur.getUserId().equals(userId))
                .collect(Collectors.toList());
    }

    public List<SysUserRole> findByRoleId(Long roleId) {
        return userRoleMap.values().stream()
                .filter(ur -> ur.getRoleId().equals(roleId))
                .collect(Collectors.toList());
    }

    public void deleteByUserIdAndRoleId(Long userId, Long roleId) {
        userRoleMap.values().removeIf(ur -> 
            ur.getUserId().equals(userId) && ur.getRoleId().equals(roleId));
    }

    public void deleteByUserId(Long userId) {
        userRoleMap.values().removeIf(ur -> ur.getUserId().equals(userId));
    }

    public void deleteByRoleId(Long roleId) {
        userRoleMap.values().removeIf(ur -> ur.getRoleId().equals(roleId));
    }
} 